import React, { Component } from 'react';
import {
	StyleSheet, Text, View, TouchableOpacity, Alert, Modal, ActivityIndicator,
	PixelRatio, TextInput, Image, ScrollView, ImageBackground, Animated
} from "react-native";
import { API, API_GENERATE } from '../../../config/api';
import MethodUtil from '../../../utils/MethodUtil';
import { GLOBAL } from '../../../config/global';
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common.js';
import { ApprovalView, RefuseModal } from '../../../component/ModalVerifylComponent.js';
import Echarts from 'native-echarts';
import { LightBox } from '../../../component/Store';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { SpaceBetween } from '../create/_components/SpaceBetween.js';
import { StepItem } from '../../enterprise/credit/component/StepItem';
import HTTP from '../../../utils/http';
import ToastUtil from '../../../utils/toast';
const scale = GLOBAL.SCALE;

const leftArrows = require('../../../imgs/credit/leftArrows.png');//闭口图标
const change = require('../../../imgs/credit/change.png');//闭口图标

export class ChangeDetailPage extends Component {
	static navigationOptions = ({ navigation, navigationOptions }) => {
		const params = navigation.state.params || {};
		return {
			headerTitle: '变更合同详情',
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.navigate('ApproveListPage', { choice: params.choice || {} }) }} color='#fff' />,
			headerRight: (<Image style={style.head.headRightEmpty} source={require('../../../imgs/goBackEmpty.png')} />),
			headerStyle: style.head.headerStyle,
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center'
			}
		}
	};

	requesting;
	constructor(props) {
		super(props);
		this.alterId = props.navigation.state.params.paramsData ? props.navigation.state.params.paramsData.alterId : '';
		this.taskId = props.navigation.state.params.paramsData ? props.navigation.state.params.paramsData.taskId : '';
		this.formKey = props.navigation.state.params.paramsData ? props.navigation.state.params.paramsData.formKey : '';
		this.taskName = props.navigation.state.params.paramsData ? props.navigation.state.params.paramsData.taskName : '';
		this.orderId = props.navigation.state.params.orderId;
		this.status = props.navigation.state.params.status;
		this.choice = props.navigation.state.params.choice || {};
		this.state = {
			data: {},
			resultModalVisible: false,
			loaded: false,
			lightBoxVisible: false,
			stateLightBoxData: false,
			stepData: [],
		};
		this._closeLightBox = this._closeLightBox.bind(this);
		this.lightBoxData = {
			onClosePress: this._closeLightBox,
			modalVisible: false,
			title: '',
			rowDataList: [],
		};
		this.nodeParams = {
			corpId: this.choice.corpId || ''
		};
	}

	componentWillMount () {
		this._getDetailData();
	}

	// 节点查询
	_findNode = async () => {
		let findNodeData = await HTTP.GET(API_GENERATE(API.FIND_NODE), this.nodeParams);
		return findNodeData || []
	}

	//初始化详情数据
	async _getDetailData () {
		this.setState({
			loaded: true
		});
		let responseData = await HTTP.POST(API_GENERATE(API.ORDER_CHANGE_DETAIL), {
			alterId: this.alterId,
			orderId: this.orderId,
			corpId: this.choice.corpId || '',
		});
		let { registerDate, processInstanceId, alterId } = responseData.orderAlterHeadVO || {};
		this.alterId = alterId;
		// 审批流程参数
		this.nodeParams = {
			processInstanceId,
			bizId: alterId,
			bizObjType: '16',
			corpId: this.choice.corpId || null,
		}

		let stepData = [];
		let findNodeData = await this._findNode();
		console.log('findNodeData00000000000000', findNodeData)
		if (findNodeData) {
			findNodeData.map((item, index) => {
				let timeData = '';
				let monthData = '';
				let timeValue = '';
				if (item.auditTime) {
					timeData = item.auditTime.split(' ');
					monthData = (timeData[0] || '').split('-');
					timeValue = monthData[1] + '月' + monthData[2] + '日';
					timeData = timeData[1].split(':');
				}
				if (index == findNodeData.length - 1) {
					stepData[index] = { logId: item.logId, day: timeValue, hour: timeData[0] + ':' + timeData[1], auditResult: item.auditResult, info: item.auditStaffName, visible: false };
				} else {
					stepData[index] = { logId: item.logId, day: timeValue, hour: timeData[0] + ':' + timeData[1], auditResult: item.auditResult, info: item.auditStaffName, visible: true };
				}
			})
		}

		if (responseData) {
			this.setState({
				data: responseData,
				stepData: stepData
			})
		}
		this.setState({
			loaded: false
		});
	}

	// animatedFn
	_animatedFn = (num, animateObj) => {
		Animated.timing(
			animateObj,
			{
				duration: 300,
				toValue: num
			}
		).start();
	}


	_closeLightBox () {
		this.lightBoxData.modalVisible = false;
		const { lightBoxVisible } = this.state;
		this.setState({
			lightBoxVisible: !lightBoxVisible,
		});
	}
	//同意，驳回接口调用
	getApprovalView () {
		//HASLOT 已审批   LOT未审批
		return (this.status && this.status === 'LOT') ? (
			<View style={{ backgroundColor: '#fff' }}>
				<ApprovalView agreePress={() => {
					this.isAgreed = '1';
					this.remark = '';
					this.setState({
						refuseModalVisible: true
					})

				}} refusePress={() => {
					this.isAgreed = '0';
					this.remark = '';
					this.setState({
						refuseModalVisible: true
					})
				}} />
			</View>
		) : null;
	}

	async _fetchApproval () {
		if (this.requesting) return;
		this.setState({
			refuseModalVisible: false,
			loaded: true
		});
		this.requesting = true;
		const responseData = await HTTP.POST(API_GENERATE(API.ORDER_CHANGE_APPROVAL), {
			//businessKey: this.businessKey,
			orderAlterHeadVO: {
				alterId: this.alterId
			},
			auditStatus: this.isAgreed == '1' ? 'PASS' : 'UNPASS',
			taskId: this.taskId,
			formKey: this.formKey,
			taskName: this.taskName,
			auditComment: this.remark, // 填写
			corpId: this.choice.corpId
		});

		this.setState({
			loaded: false
		});

		if (responseData) {
			ToastUtil.showSuccess((this.isAgreed == '0') ? '驳回成功' : '审批成功').then(() => { this._goBack(); })
		} else {
			this.requesting = false;
		}
	}

	// 返回上一个页面
	_goBack = () => {
		setTimeout(() => {
			this.requesting = false;
		}, 1000)
		this.props.navigation.navigate('HomePage');
	}

	getEcharts (clitem) {
		let { creditAmount, usedAmount } = clitem;
		let crAmount = MethodUtil.countObj.multiply(MethodUtil.countObj.divide(usedAmount, creditAmount, 2), 100);
		let usAmount = MethodUtil.countObj.subtract(100, crAmount);
		//<Text style={{ marginBottom: 8 * scale, fontSize: 13 * scale, color: '#404040' }}>总授信额度:{MethodUtil.toThousands(clitem.creditAmount)}</Text>
		//<Text style={{ marginBottom: 8 * scale, fontSize: 13 * scale, color: '#404040' }}>占用:{MethodUtil.toThousands(clitem.usedAmount)}</Text>
		//<Text style={{ fontSize: 13 * scale, color: '#2F7BFF' }}>可用:{MethodUtil.toThousands(MethodUtil.countObj.subtract(clitem.creditAmount, clitem.usedAmount))}</Text>
		let option = {
			tooltip: {
				trigger: 'item',
				formatter: "{a} <br/>{b}: {c} ({d}%)"
			},
			color: ['#2F7BFF', style.color.bgGray],
			legend: {
				show: false
			},
			series: [
				{
					type: 'pie',
					radius: ['60%', '70%'],
					avoidLabelOverlap: false,
					hoverAnimation: false,
					label: {
						normal: {
							show: false,
							position: 'center',
							formatter: '{c}%'
						}
					},
					labelLine: {
						normal: {
							show: false
						}
					},
					data: [
						{
							value: usAmount, name: '可用额度', label: {
								normal: {
									show: true
								}
							}
						},
						{ value: crAmount, name: '占用额度' },
					]
				}
			]
		};
		return option;
	}

	//批次关联
	async _didPressShowOppoOrderLightBox (data) {
		let { orderInfoVO, oitem } = data
		this.lightBoxData.rowDataList = [];
		this.lightBoxData.modalVisible = true;
		this.lightBoxData.title = '商品信息';
		this.lightBoxData.rowDataList.push({ label: '采购批次号：', val: oitem.batchNo || '' });
		this.lightBoxData.rowDataList.push({ label: '商品名称：', val: oitem.goodsName || '' });
		this.lightBoxData.rowDataList.push({ label: '包装/规格：', val: oitem.packagingSpec || '' });
		this.lightBoxData.rowDataList.push({ label: '计量单位：', val: oitem.uom || '吨' });
		this.lightBoxData.rowDataList.push({ label: '订货量：', val: oitem.quantity || 0 });
		this.lightBoxData.rowDataList.push({ label: '溢短装比率：', val: MethodUtil.countObj.multiply(oitem.ysPercent, 100) + '%' });
		this.lightBoxData.rowDataList.push({ label: '含税采购价：', val: MethodUtil.toThousands(oitem.price, 2) });
		if (oitem.tempPriceFormulaDesc) {
			this.lightBoxData.rowDataList.push({ label: '结算价定价模式：', val: oitem.tempPriceFormulaDesc });
		}
		if (oitem.udPrice) {
			this.lightBoxData.rowDataList.push({ label: '升贴水：', val: oitem.udPrice || 0 });
		}
		this.lightBoxData.rowDataList.push({ label: '含税总金额：', val: MethodUtil.toThousands(oitem.amount, 2) });
		this.lightBoxData.rowDataList.push({ label: '交货方式：', val: orderInfoVO.orderType == 'P' ? orderInfoVO.purchaseDeliveryTypeName : orderInfoVO.saleDeliveryTypeName });
		this.lightBoxData.rowDataList.push({ label: '出库地点：', val: oitem.deliveryAddressName });
		this.lightBoxData.rowDataList.push({ label: '交货起始日期：', val: oitem.deliveryBeginDate });
		this.lightBoxData.rowDataList.push({ label: '交货截至日期：', val: oitem.deliveryEndDate });
		this.lightBoxData.rowDataList.push({ label: '运输方式：', val: oitem.transportTypeName || '' });
		this.lightBoxData.rowDataList.push({ label: '付款类型：', val: orderInfoVO.payTypeName || '' });
		this.lightBoxData.rowDataList.push({ label: '付款方式：', val: orderInfoVO.payStyleName || '' });
		this.lightBoxData.rowDataList.push({ label: '途损率：', val: '千分之' + MethodUtil.countObj.multiply(orderInfoVO.lostRate || 0, 1000) });
		this.lightBoxData.rowDataList.push({ label: '业务员：', val: orderInfoVO.bizStaffName || '' });

		const { lightBoxVisible } = this.state;
		this.setState({
			lightBoxVisible: !lightBoxVisible
		});
	}



	render () {
		let { stepData, data } = this.state;
		//订单主项信息，订单主项变更信息,订单商品变更信息
		let { auditLogVOs, creditInfoVOs, auditResultName, orderInfoVO, orderAlterHeadVO, orderAlterLineVOs, orderItemVOs } = data;
		let { orderId, companyName, orderType, isFuture, bizMode } = orderInfoVO || {};
		let { alterReason, alterStatus, alterStatusName } = orderAlterHeadVO || {};
		const approvalView = this.getApprovalView();
		return (
			<View style={styles.container}>
				<View style={[styles.emptyBg, { flexDirection: 'row' }]}>
					<View style={{ paddingLeft: 30 * scale, width: 320 * scale }}>
						<Text style={{ color: '#fff', fontSize: 16 * scale, }}>{orderId}</Text>
						<Text style={{ color: '#fff', fontSize: 12 * scale, marginTop: 8 * scale, marginBottom: 8 * scale }}>{companyName}</Text>
						<Text style={{ fontSize: 10 * scale, color: '#fff' }}>(业务组织：{this.choice.corpName || '-'})</Text>
					</View>
					<TouchableOpacity onPress={() => {
						if (bizMode && bizMode == 1) {
							this.props.navigation.navigate('OrderDetailsPage', {
								orderId: orderId,
								orderType: orderType,
								isFuture: isFuture,
								choice: this.choice
							})
						} else {
							this.props.navigation.navigate('OrderDetailsPage', {
								orderId: orderId,
								orderType: orderType,
								isFuture: isFuture,
								choice: this.choice
							})
						}
					}}>
						<View style={{ marginTop: 10 * scale }}>
							<Image source={leftArrows}></Image>
						</View>
					</TouchableOpacity>
				</View>
				<ScrollView>
					{
						orderAlterLineVOs && orderAlterLineVOs.length > 0 ?
							(<View>
								{
									orderAlterLineVOs.map((item, i) => {
										return (
											<View style={[styles.itemBox, styles.borders]} key={i}>
												<Text style={styles.itemTitle}>{item.alterType || ''}</Text>
												<View style={[styles.borderCss, { flexDirection: 'row' }]}>
													<Text numberOfLines={4} style={[styles.fontCss, styles.leftText, { flex: 1 }]}>{item.columnDesc || ''}</Text>
													<Text numberOfLines={4} style={[styles.fontCss, { flex: 1 }]}>{item.beforeValueDesc || ''}</Text>
													<Image source={change} style={[styles.imageCss]}></Image>
													<Text numberOfLines={4} style={[styles.fontCss, { flex: 1 }]}>{item.afterValueDesc || ''}</Text>
												</View>
												<View style={[styles.remarkView]}>
													<Text style={[styles.fontCss]}>备注:{item.remark || ''}</Text>
												</View>
											</View>
										)
									})
								}
								<View style={{ width: '100%', height: 12 * scale, backgroundColor: style.color.bgGray }}></View>
							</View>)
							: null
					}
					{
						orderItemVOs ? (<View>

							{
								orderItemVOs.map((oitem, i) => {
									let { orderAlterLineVOs } = oitem;
									return (
										<View key={'order' + 'i'}>

											<View style={[styles.itemBox, styles.borders,]}>
												<TouchableOpacity activeOpacity={0.5} onPress={() => {
													this._didPressShowOppoOrderLightBox({
														orderInfoVO: orderInfoVO, oitem: oitem
													}
													)
												}}>
													<View style={[styles.goodsView]}>
														<View style={{ flexDirection: 'row', marginTop: 12 * scale }}>
															<Text style={[styles.goodsIdCss]}>{i + 1}</Text>
															<Text style={[styles.pbatchCss]}>采购批次号:{oitem.batchNo || ''}</Text>
														</View>
														<View style={{ flexDirection: 'row', marginTop: 9 * scale }}>
															<Text style={[styles.goodsNameCss, styles.goodsWeightCss]} > 产品名称: {oitem.goodsName || ''}</Text>
															<Text style={[styles.goodsWeightCss]}>订货量:{oitem.quantity}{oitem.uom}</Text>
														</View>
													</View>
												</TouchableOpacity>
											</View>
											{
												orderAlterLineVOs ? (<View>
													{
														orderAlterLineVOs.map((olitem, j) => {
															return (
																<View style={[styles.itemBox, styles.borders]} key={'oitem' + i + j}>
																	<Text style={styles.itemTitle}>{olitem.alterType || ''}</Text>
																	<View style={[styles.borderCss, { flexDirection: 'row', }]}>
																		<Text style={[styles.fontCss, styles.leftText]}>{olitem.columnDesc || ''}</Text>
																		<Text style={[styles.fontCss, { width: 100 * scale, textAlign: 'center' }]}>{olitem.beforeValueDesc || ''}</Text>
																		<Image source={change} style={[styles.imageCss]}></Image>
																		<Text style={[styles.fontCss, { width: 100 * scale, textAlign: 'center' }]}>{olitem.afterValueDesc || ''}</Text>
																	</View>
																	<View style={[styles.remarkView, orderAlterLineVOs.length == 1 || orderAlterLineVOs.length - 1 == j ? null : styles.borderCss]}>
																		<Text style={[styles.fontCss]}>备注:{olitem.remark}</Text>
																	</View>
																</View>)
														})
													}
												</View>) : null
											}
										</View>
									)
								})
							}
							<View style={{ width: '100%', height: 12 * scale, backgroundColor: style.color.bgGray }}></View>
						</View>) : null
					}
					{
						creditInfoVOs ?
							(<View>
								{
									creditInfoVOs.map((clitem, j) => {
										let optionData = this.getEcharts(clitem);
										return (
											(orderInfoVO.orderType == 'P' && clitem.companyType == '1') || (orderInfoVO.orderType == 'S' && clitem.companyType == '2') ?
												<View style={[styles.itemBox, styles.borders,]} key={'credit' + j}>
													<Text style={styles.itemTitle}>授信占用</Text>
													<View style={[styles.borderCss, { flexDirection: 'row', height: 100 * scale }]}>
														<View style={{ width: 100 * scale, height: 100 * scale, }}>
															<Echarts height={100 * scale} width={100 * scale} option={optionData} />
														</View>
														<View style={{ marginTop: 12 * scale }}>
															<Text style={{ marginBottom: 8 * scale, fontSize: 13 * scale, color: '#404040' }}>总授信额度:{MethodUtil.toThousands(clitem.creditAmount)}</Text>
															<Text style={{ marginBottom: 8 * scale, fontSize: 13 * scale, color: '#404040' }}>占用:{MethodUtil.toThousands(clitem.usedAmount)}</Text>
															<Text style={{ fontSize: 13 * scale, color: '#2F7BFF' }}>可用:{MethodUtil.toThousands(MethodUtil.countObj.subtract(clitem.creditAmount, clitem.usedAmount))}</Text>
														</View>
													</View>
												</View> : null)
									})
								}
							</View>) : null
					}
					{orderAlterHeadVO && orderAlterHeadVO.attachmentId && creditInfoVOs && creditInfoVOs.length > 0 ? <View style={{ width: '100%', height: 12 * scale, backgroundColor: style.color.bgGray }}></View>
						: null}
					{orderAlterHeadVO && orderAlterHeadVO.attachmentId ? <View style={[styles.itemBox, styles.borders]}>
						<Text style={styles.itemTitle}>附件</Text>
						{
							orderAlterHeadVO.attachmentId.split(',').map((olitem, j) => {
								return (
									<TouchableOpacity key={'cont' + j} onPress={() => {
										this.props.navigation.navigate('ContractPdfPage', {
											finalFileId: olitem
										});
									}}>
										<SpaceBetween fontLeft={{ title: '补充合同' }} fontRight={{ title: '' }} iconShow={true} />
									</TouchableOpacity>)
							})

						}
						{
							stepData && stepData.length > 0 ? (
								<View style={[styles.fromItemBox, styles.fromItemBoxEnd]}>
									{
										stepData && stepData.map((item, index) => {
											return (
												<StepItem {...item} key={index} />
											)
										})
									}
								</View>
							) : null
						}
					</View> : null}
					{orderAlterHeadVO && orderAlterHeadVO.attachmentId ? <View style={{ width: '100%', height: 12 * scale, backgroundColor: style.color.bgGray }}></View> : null}

					{alterReason ? <View style={[styles.itemBox, styles.borders,]}>
						<Text style={styles.itemTitle}>变更原因</Text>
						<SpaceBetween fontLeft={{ title: '原因说明' }} fontRight={{ title: alterReason }} iconShow={false} />
					</View> : null}

					<LightBox {...this.lightBoxData} />
				</ScrollView>
				{
					this.status == 'SHOW' || this.status == 'HASLOT' ?
						<View style={styles.bottomBtnCell}>
							<Text style={[styles.statusCss, { color: alterStatus == 'UNPASS' ? '#FC5454' : '#2F7BFF' }]}>{alterStatusName}</Text>
						</View> : null
				}
				{approvalView}
				<RefuseModal
					titleText={'审批意见'}
					placeholderText={this.isAgreed == '1' ? '请输入同意原因' : null}
					propsDefaultValue={this.isAgreed == '1' ? '审批同意' : '审批驳回'}
					visible={this.state.refuseModalVisible}
					btnPress={(remark) => {
						this.remark = remark;
						this._fetchApproval();
					}} bgPress={() => {
						this.setState({
							refuseModalVisible: false,
						});
					}} />

				{
					this.state.loaded ?
						<View style={{ position: 'absolute', height: '100%', width: '100%', top: 0 }}>
							<PageStatusIndex status='loading' />
						</View>
						: null
				}
			</View >
		)
	}
}
const styles = StyleSheet.create({

	container: {
		flex: 1,
		backgroundColor: style.color.white,
		height: '100%'
	},
	emptyBg: {
		height: 69 * scale,
		backgroundColor: style.color.themeColor,
	},
	itemBox: {
		paddingLeft: 12 * scale,
		paddingRight: 12 * scale,
	},
	borders: {
		//borderTopWidth: 12 * scale,
		borderStyle: 'solid',
		borderTopColor: style.color.dullGrey,
	},
	itemTitle: {
		fontSize: 14 * scale,
		color: '#404040',
		height: 20 * scale,
		lineHeight: 20 * scale,
		marginTop: 12 * scale,
		marginBottom: 12 * scale
	},
	fontCss: {
		fontSize: 13 * scale,
		color: '#404040'
	}, leftText: {
		width: 100 * scale,
	}, borderCss: {
		borderBottomWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderBottomColor: style.color.border,
		//height: 35 * scale
		paddingBottom: 13 * scale
	}, remarkView: {
		marginTop: 13 * scale,
		marginBottom: 13 * scale
	}, imageCss: {
		width: 16 * scale,
		height: 16 * scale,
		marginLeft: 12 * scale,
		marginRight: 12 * scale
	}, marginView: {
		marginTop: 12 * scale
	},
	bottomBtnCell: {
		width: 375 * scale,
		height: 60 * scale,
		borderTopColor: '#e4e4e4',
		borderTopWidth: 1 / PixelRatio.get(),
		backgroundColor: '#fff',
	}, statusCss: {
		height: 60 * scale,
		width: 375 * scale,
		textAlign: 'center',
		lineHeight: 60 * scale,
		fontSize: 18 * scale
	},//商品css
	goodsView: {
		marginTop: 15 * scale,
		height: 70 * scale, borderWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderColor: style.color.border,
	}, goodsIdCss: {
		marginLeft: 12 * scale,
		textAlign: 'center',
		width: 20 * scale,
		height: 20 * scale,
		backgroundColor: '#E2E9FF',
		borderRadius: 4 * scale,
	}, goodsNameCss: {
		width: 150 * scale,
		marginLeft: 40 * scale,
	}, goodsWeightCss: {
		fontSize: 12 * scale,
		color: '#405976',
		textAlign: 'center'
	}, pbatchCss: {
		fontSize: 14 * scale,
		color: '#405976',
		paddingLeft: 6 * scale
	}, fromItemBox: {
		backgroundColor: style.color.white,
		paddingLeft: 15 * scale,
		paddingRight: 15 * scale,
		marginBottom: 12 * scale
	}, fromItemBoxEnd: {
		paddingTop: 40 * scale,
		paddingLeft: 40 * scale,
		paddingBottom: 40 * scale,
		marginBottom: 0
	}
})